package common.db.handlers;

import common.db.RowProcessor;

import java.util.ArrayList;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Contains basic functionality for handlers that convert data into List of some objects.
 */
public abstract class ListHandler<E>  implements ResultSetHandler<List<E>>
{


	public List<E> handle(ResultSet rs)
	{
		try
		{
			List<E> list = new ArrayList<E>();
			while (rs.next())
			{
				try
				{
					E item = processRow(rs);
					if (item != null || isAddNulls())
						list.add(item);
				}
				catch (SQLException e)
				{
					if (!isSuppressExceptions())
						throw e;	
				}
			}
			return list;

		}
		catch (SQLException e)
		{
			throw new RuntimeException(e);           // trebalo bi da signaliziramo nekom sql greskom
		}
	}



	public static <E> ListHandler<E> getInstance(final RowProcessor<E> rowProcessor)
	{
		return new ListHandler<E>()
		{
			protected E processRow(ResultSet rs) throws SQLException
			{
				return rowProcessor.processRow(rs);
			}
		};
	}

	public static <E> ListHandler<E> getInstance(final RowProcessor<E> rowProcessor, final boolean addNulls)
	{
		return new ListHandler<E>()
		{
			protected E processRow(ResultSet rs) throws SQLException
			{
				return rowProcessor.processRow(rs);
			}

			@Override
			protected boolean isAddNulls()
			{
				return addNulls;
			}
		};
	}

	@Deprecated
	public static <E> ListHandler<E> getSEInstance(final RowProcessor<E> rowProcessor)
	{
		return new ListHandler<E>()
		{
			protected E processRow(ResultSet rs) throws SQLException
			{
				return rowProcessor.processRow(rs);
			}

			@Override
			protected boolean isSuppressExceptions()
			{
				return true;
			}
		};
	}

	protected abstract E processRow(ResultSet rs) throws SQLException;

	protected boolean isSuppressExceptions()
	{
		return false;
	}

	protected boolean isAddNulls()
	{
		return true;
	}
}
